<script setup lang="ts" name="JxtechSvgIcon">
import { reactive, CSSProperties, watch, onMounted, ref } from "vue";
defineOptions({ name: "JxtechSvgIcon" });
const svgRef = ref();

export type SvgIconProps = {
  /**图标 */
  icon: string;
  /**大小 */
  size?: number;
  /**颜色 */
  color?: string;
  /**图标的前缀 ==> 非必传（默认为"icon"） */
  prefix?: string;
  /**样式 */
  iconStyle?: CSSProperties; // 图标的样式 ==> 非必传
};

const props = withDefaults(defineProps<SvgIconProps>(), {
  prefix: "icon",
  iconStyle: () => ({})
});

const IconState = reactive({
  iconName: "",
  iconSize: "",
  parsePropsIcon(icon: string, size: number) {
    IconState.iconName = `#${props.prefix}-${icon}`;
    IconState.iconSize = size ? size + "px" : "1.2em";
  }
});
IconState.parsePropsIcon(props.icon, props.size);

watch(
  () => props.icon,
  val => {
    IconState.parsePropsIcon(val, props.size);
  }
);
watch(
  () => props.size,
  val => {
    IconState.parsePropsIcon(props.icon, val);
  }
);

onMounted(() => {
  svgRef.value.style.color = props.color;
});
</script>

<template>
  <svg class="icon" aria-hidden="true" :font-size="IconState.iconSize" :style="iconStyle" ref="svgRef">
    <use :xlink:href="IconState.iconName"></use>
  </svg>
</template>

<style lang="scss" scoped></style>
